package pub.cleangao.mybatis.spi;

import pub.cleangao.mybatis.annotation.Dialect;

public class DatabaseMeta {

    private String dbType;
    private String jdbcUrl;
    private String serviceNode;
    private Dialect dialect;

    public DatabaseMeta(String jdbcUrl) {
        if (jdbcUrl.contains("?")) {
            jdbcUrl = jdbcUrl.substring(0, jdbcUrl.indexOf("?"));
        }
        this.jdbcUrl = jdbcUrl;
        // 去除: `jdbc:`
        jdbcUrl = jdbcUrl.substring(5);
        int fsp = jdbcUrl.indexOf(":");
        // oracle | sqlserver | sqlite | postgresql | mysql
        dbType = jdbcUrl.substring(0, fsp);
        jdbcUrl = jdbcUrl.substring(fsp + 1);
        //
        switch (dbType) {
            case "oracle" -> {
                serviceNode = jdbcUrl.substring("thin:@".length());
                dialect = Dialect.Oracle;
            }
            case "mysql" -> {
                serviceNode = jdbcUrl;
                dialect = Dialect.MySQL;
            }
            case "mariadb" -> {
                serviceNode = jdbcUrl;
                dialect = Dialect.Mariadb;
            }
            case "sqlserver" -> {
                serviceNode = jdbcUrl;
                dialect = Dialect.SqlServer;
            }
            case "sqlite" -> {
                serviceNode = jdbcUrl;
                dialect = Dialect.SQLite;
            }
            case "postgresql" -> {
                serviceNode = jdbcUrl;
                dialect = Dialect.Postgres;
            }
        }
    }

    public String getServiceNode() {
        return serviceNode;
    }

    public Dialect getDialect() {
        return dialect;
    }

    public String getDbType() {
        return dbType;
    }

    public String getJdbcUrl() {
        return jdbcUrl;
    }
}
